package Gui;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.Toolkit;
import Engine.*;
public class LoginWindow implements ActionListener {
    
    JFrame loginWindow;
    Container loginWindowContainer;
    JPanel loginPanel;
    JLabel infoField;
    JLabel nameField;
    JTextField nameTextField;
    JButton closeButton;
    JButton loginButton;
    
    public LoginWindow() {
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        
        closeButton = new JButton("close");
        closeButton.addActionListener(
              new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        }
        );
        
        loginButton = new JButton("login");
        loginButton.setActionCommand("login");
        loginButton.addActionListener(this);
        
        infoField = new JLabel("<html>You must authenticate to start test-o-matic session.<br> Please type your name.</html>",SwingConstants.CENTER);
        nameTextField = new JTextField();
        
        nameField = new JLabel("student name: ");
        nameTextField = new JTextField(18);
        
        JPanel fieldPanel = new JPanel();
        fieldPanel.setLayout(new FlowLayout());
        
        JPanel buttonPanel = new JPanel();
        buttonPanel.setLayout(new FlowLayout());
        buttonPanel.add(closeButton);
        buttonPanel.add(loginButton);
        
        fieldPanel.add(nameField);
        fieldPanel.add(nameTextField);
          
        loginWindow = new JFrame("test-o-matic login");
        loginWindow.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        
        loginWindowContainer = loginWindow.getContentPane();
        loginWindowContainer.setLayout(new BorderLayout());
        loginWindowContainer.add(infoField,"North");
        loginWindowContainer.add(fieldPanel,"Center");
        loginWindowContainer.add(buttonPanel,"South");
        loginWindow.setSize(350,120);
        loginWindow.setVisible(true);
        loginWindow.setLocation((screenSize.width-350)/2,(screenSize.height-120)/2);
    }

    public void actionPerformed(ActionEvent ae) {
        if(ae.getActionCommand().equals("login")) {
            String newStudentName = nameTextField.getText();
            if(!newStudentName.equals("")) {
                Engine.doLogin(newStudentName);
                loginWindow.setVisible(false);
            } else {
                JOptionPane.showMessageDialog(null,"Name cannot be empty. Please type your name.","empty name",JOptionPane.ERROR_MESSAGE);
            }
        }
    }
    
    
}
